package com.yb.framework.fastdfs;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;

@Component
public class FastDFSClient {
	
	@Autowired
    private FastFileStorageClient storageClient;
	
	public String uploadFile(MultipartFile file) throws IOException {
		// 源文件名
		String originalFileName = file.getOriginalFilename();
		// 文件后缀名
		String fileExtName = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
		StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), fileExtName, null);
		// fullPath = group + "/" + path
		return storePath.getFullPath();
	}
	
    public byte[] downloadFile(String filePath) {
    	String groupName = filePath.substring(0, filePath.indexOf("/"));
        String path = filePath.substring(filePath.indexOf("/") + 1);
        return storageClient.downloadFile(groupName, path, new DownloadByteArray());
	}
    
    public void deleteFile(String filePath) {
    	String groupName = filePath.substring(0, filePath.indexOf("/"));
        String path = filePath.substring(filePath.indexOf("/") + 1);
    	storageClient.deleteFile(groupName, path);
	}
}
